package authority.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import authority.comm.Message;
import authority.comm.Page;
import authority.entity.Permission;
import authority.entity.Role;
import authority.entity.User;
import authority.service.PermissionService;
import authority.service.RoleService;
import authority.util.CommonUtil;

import com.alibaba.fastjson.JSON;
/**
 * 角色servlet
 * @author shichenyang
 *
 */
@WebServlet("/roleServlet")
public class RoleServlet extends HttpServlet {
	private static final long serialVersionUID = -5213991032957567653L;
	
	private RoleService service=new RoleService();
	
	private PermissionService permissionService=new PermissionService();
	public RoleServlet() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String opr=request.getParameter("opr");
		
		PrintWriter out = response.getWriter();
		if("list".equals(opr)){//显示用户列表
			Integer start=CommonUtil.objectToInteger(request.getParameter("start"));
			Integer length=CommonUtil.objectToInteger(request.getParameter("length"));
			Page page= service.findListByPage(start, length, new Role());
			out.print(JSON.toJSONStringWithDateFormat(page, "yyyy-MM-dd HH:mm:ss"));
		}
		
		if("addBefore".equals(opr)){//添加角色之前，加载权限
			List<Permission> l= permissionService.findAllPermission();
			request.setAttribute("list", l);
			request.getRequestDispatcher("/admin/admin-role-add.jsp").forward(request, response);
		}
		
		if("add".equals(opr)){//添加角色
			String name=request.getParameter("name");
			String remarks=request.getParameter("remarks");
			String [] permissons=request.getParameterValues("permission");
			Message message= service.addRole(name, remarks, permissons, (User) request.getSession().getAttribute("user"));
			out.print(JSON.toJSONString(message));
		}
		out.flush();
		out.close();
	}

}
